let zjhRoom = require("../data/zjhRoom.class");
let JoinRoomState = require("../data/JoinRoomState");
let MessageId = require("../data/MessageId");
let EventListener = require("../core/EventListener.class");
class RoomManager{
    static getInstance(){
        if (!RoomManager._instance) {
            RoomManager._instance = new RoomManager();
        }
        return RoomManager._instance;
    }
    constructor(){
        let self = this;
        self.className = "RoomManager";
        self.rooms = {};
        self.nexRoomId = 100000;

        EventListener.getInstance().addListener(self.className, MessageId.DestroyRoom, function (data) {
            self.removeRoom(data["roomId"]);
        });
    }
    joinRoom(user, roomId){
        console.log("加入房间【" + roomId + "】");
        if (this.rooms.hasOwnProperty(roomId)) {
            if (this.rooms[roomId].getUserCount() < this.rooms[roomId].getMaxPlayer()) {
                this.rooms[roomId].addPlayer(user.getInfo());
                let message = this.rooms[roomId].getConfig();
                message.errorCode = JoinRoomState.Success;
                return message;
            } else {
                return {errorCode: JoinRoomState.Full, errorMsg: "房间人数已满！"};
            }
        }
        return {errorCode: JoinRoomState.Unkown, errorMsg: "房间不存在！"};
    }
    createRoom(roomData){
        let room = null;
        switch (roomData["mapId"]){
            case 1101:
                break;
            case 1102:
                roomData["roomId"] = this.nexRoomId;
                room = new zjhRoom(roomData);
                break;
            default:
                console.log("未知类型mapId");
                break;
        }
        this.addRoom(room);
        return room;
    }
    addRoom(room){
        if (room){
            this.nexRoomId++;
            this.rooms[room.getRoomId()] = room;
            console.log("创建房间【" + room.getRoomId() +"】最大人数【" + this.rooms[room.getRoomId()].getMaxPlayer() + "】");
        }
    }
    removeRoom(roomId){
        if (this.rooms.hasOwnProperty(roomId)){
            delete this.rooms.roomId;
            this.nexRoomId--;
            console.log("销毁房间【"+roomId+"】");
        }
    }
}
RoomManager._instance = null;
module.exports = RoomManager;